import { ComponentType, createContext, useContext, useState, Component } from "react";
import styles from "./index.module.css";
import { createPortal } from "react-dom";

interface HomeLoadingContext {
    loading: boolean,
    setLoading: React.Dispatch<React.SetStateAction<boolean>> | (() => Error)
}

function HomeLoading() {
    const { loading } = useContext(LoadingContext);

    return loading ? (
        <>{
            createPortal((
                <div className={styles.modalMask}>
                    <div className={styles.skCubeGrid}>
                        <div className={`${styles.skCube} ${styles.skCube1}`}></div>
                        <div className={`${styles.skCube} ${styles.skCube2}`}></div>
                        <div className={`${styles.skCube} ${styles.skCube3}`}></div>
                        <div className={`${styles.skCube} ${styles.skCube4}`}></div>
                        <div className={`${styles.skCube} ${styles.skCube5}`}></div>
                        <div className={`${styles.skCube} ${styles.skCube6}`}></div>
                        <div className={`${styles.skCube} ${styles.skCube7}`}></div>
                        <div className={`${styles.skCube} ${styles.skCube8}`}></div>
                        <div className={`${styles.skCube} ${styles.skCube9}`}></div>
                    </div>
                </div>
            ), document.body)
        }</>
    ) : <></>
}

const defaultContext: HomeLoadingContext = {
    loading: false,
    setLoading: () => new Error('setLoading not init!')
}

const LoadingContext = createContext(defaultContext);

export function useLoader() {
    return useContext(LoadingContext);
}

function LoaderWarper({children}: {
    children: JSX.Element
}) {
    const [loading, setLoading] = useState(false);

    return (
        <LoadingContext.Provider value={{ loading, setLoading }}>
            {children}
            <HomeLoading />
        </LoadingContext.Provider>
    )
}

export function InitHomeLoader(Loading: ComponentType) {
    return class NewClass extends Component {
        render() {
            return (
                <LoaderWarper>
                    <Loading {...this.props} />
                </LoaderWarper>
            )
        }
    }
}